package org.zoomdev.zoom.web.view.impl;

import jakarta.servlet.http.HttpServletResponse;
import org.zoomdev.zoom.common.io.Io;
import org.zoomdev.zoom.web.utils.MediaType;
import org.zoomdev.zoom.web.view.View;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

public abstract class OutputStreamView implements View {

    private String name;

    public OutputStreamView() {
    }

    public OutputStreamView(String name) {
        this.name = name;
    }

    @Override
    public void render(HttpServletResponse response) throws Exception {
        OutputStream os = null;
        try {
            String name = getName();
            response.setContentType(MediaType.STREAM.type());
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    URLEncoder.encode(name, response.getCharacterEncoding()));
            os = response.getOutputStream();
            writeTo(os);
        } finally {
            try {
                close();
            } catch (Throwable t) {

            }
            Io.close(os);
        }

    }

    protected String getName() {
        return name;
    }

    protected abstract void writeTo(OutputStream outputStream) throws IOException;

    protected abstract void close() throws IOException;
}
